<template>
  <div class="port-wrap">
    <loading v-show='!show'></loading> 
    <div class="page-title">
      <h3>{{$t('realTime.navBtn2')}}</h3>
    </div>
    <transition name='fade'>
      <div class="body"  v-show='show'>   
        <portpic :eths="eths" :length='length'></portpic>
        <porttable :eths="eths"></porttable> 
      </div>
    </transition> 
  </div>
</template>
<script>
import portpic from './port/portpic.vue'
import porttable from './port/porttable.vue'
import realTimeService from 'services/realTimeService'
import loading from 'components/common/loading'
export default {
  data: function() {
    return {
      eths: [],
      intervalid: null,
      length:0,
      show:false,
      clearTimeout:false
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    loadData() {
      realTimeService.getEthsState()
      .then((res) => {
        
        if (res.errcode === 0) {
          this.show=true
          this.length=res['9'].length
          this.eths = res['9'].map((item) => {
						return {
							name: item.name,
							inpkts: item.in_packets,
							outpkts: item.out_packets,
							inbytes: this.convertFlow(item.in_bytes),
							outbytes: this.convertFlow(item.out_bytes),
              in_bps:item.in_Bps,
              out_bps:item.out_Bps,
              in_err:item.in_errors,
              out_err:item.out_errors,
              in_drop:item.in_dropped,
              out_drop:item.out_dropped,
							status: Number(item.up)
						}
					})
        }
        if (this.clearTimeout) {
        	return 
        }  
        clearTimeout(this.intervalid)
        this.intervalid = setTimeout(() => this.loadData(), 1000)
			},()=>{
				if (this.clearTimeout) {
        	return 
        }
				clearTimeout(this.intervalid)
				this.intervalid = setTimeout(() => this.loadData(), 1000)
			})
    },
    convertFlow(bps) {
			let flow = ''
			if (bps < 1024) {
				flow = Math.ceil(bps) + ' B'
			}
			if (bps >= 1024 && bps < 1024*1024) {
				flow = bps/1024
				flow = flow.toFixed(2) + ' KB'
			}
			if (bps >= 1024*1024 && bps < 1024*1024*1024) {
				flow = bps/1024/1024
				flow = flow.toFixed(2) + ' MB'
			}
			if (bps >= 1024*1024*1024) {
				flow = bps/1024/1024/1024
				flow = flow.toFixed(2) + ' GB'
			}
			return flow
	  }
  },
  beforeDestroy() {
    this.clearTimeout	 = true
    clearTimeout(this.intervalid)
  },
  components: {
    portpic,
    porttable,
    loading
  }
}
</script>